import { notification } from 'antd';
import { Toast } from 'antd-mobile';
import { renderToString } from 'react-dom/server';
import { enquireScreen } from 'enquire-js';

let isMobile;
enquireScreen(b => {
  isMobile = b;
});

/**
 * 包装系统的console
 *
 * @param {string} obj 要打印的数据
 * @param {string} [mark='未定义标签'] 提示标签
 * @param {string} [moudle='none'] 模块名称
 */
export const print = (obj, mark = '未定义标签', moudle = 'none') => {
  console.log(`${moudle} >>> ${mark}: `, obj);
};
/**
 * 显示接口返回错误信息
 * @param message
 * @param response
 */
export const showError = (api, response) => {
  if (isMobile) {
    Toast.fail(typeof response.message === 'string' ? response.message : '操作失败');
  } else {
    notification.error({
      message: `${api.title}失败`,
      description: typeof response.message === 'string' ? response.message : '操作失败',
    });
  }
  console.log('接口调用失败 >>> ', {
    api: api.url,
    msg: response.message,
    data: JSON.stringify(response.entity),
  });
};
/**
 * 显示操作成功信息
 * @param description
 */
export const showSuccess = (api, extra) => {
  if (isMobile) {
    Toast.success(`${api.title}成功${extra ? `，${extra}` : ''}`);
  } else {
    notification.success({
      message: '操作成功',
      description: `${api.title}成功${extra ? `，${extra}` : ''}`,
      duration: 2,
    });
  }
};
/**
 * 获取路径查询参数
 * @param key
 * @returns {string | null}
 */
export const getSearchParamByKey = key => {
  const urlParams = new URL(window.location.href);
  return urlParams.searchParams.get(key);
};
/**
 * 获取路径查询参数
 * @returns {{}}
 */
export const getSearchParams = () => {
  const urlParams = new URL(window.location.href);
  const params = {};
  for (const [key, value] of urlParams.searchParams.entries()) {
    params[key] = value;
  }
  return params;
};
/**
 * 打开最大化新窗口
 * @param component
 */
export const openMax = component => {
  const iWidth = window.screen.width;
  const iHeight = window.screen.height - 100;
  const iTop = (window.screen.availHeight - 30 - iHeight) / 2;
  const iLeft = (window.screen.availWidth - 10 - iWidth) / 2;
  const newWin = window.open(
    '',
    'print',
    `width=${iWidth}, height=${iHeight},top=${iTop},left=${iLeft},toolbar=no, menubar=no, scrollbars=no, resizable=no,location=no, status=no,alwaysRaised=yes,depended=yes`
  );
  newWin.document.write(renderToString(component));
};
/**
 * 文件下载
 * @param url
 * @param params
 */
export const download = (url, params) => {
  window.location.href = encodeURI(getSearchPath(url, params));
};
export const getSearchPath = (url, params) => {
  let paramStr = '?';
  if (params && !isEmptyObject(params)) {
    Object.keys(params).forEach(key => {
      paramStr += `${key}=${params[key]}&`;
    });
  }
  return url + paramStr;
};
/**
 * 打印报表
 * @param component
 */
export const printReport = component => {
  const iWidth = window.screen.width;
  const iHeight = window.screen.height - 100;
  const iTop = (window.screen.availHeight - 30 - iHeight) / 2;
  const iLeft = (window.screen.availWidth - 10 - iWidth) / 2;
  const newWin = window.open(
    '',
    'print',
    `width=${iWidth}, height=${iHeight},top=${iTop},left=${iLeft},toolbar=no, menubar=no, scrollbars=no, resizable=no,location=no, status=no,alwaysRaised=yes,depended=yes`
  );
  const str = renderToString(component)
    .replace(
      '<table',
      '<table cellspacing=0 width="100%" style="border-right:1px solid #000;border-bottom:1px solid #000" '
    )
    .replace(/<th /g, '<th style="border-left:1px solid #000;border-top:1px solid #000" ')
    .replace(/<td /g, '<th style="border-left:1px solid #000;border-top:1px solid #000" ')
    .replace(
      '<table class="ant-table-fixed">',
      '<table class="ant-table-fixed" style="display: none;">'
    );
  newWin.document.write(str);
  newWin.print();
};
/**
 * 判断是否为空对象
 * @param obj
 * @returns {boolean}
 */
export const isEmptyObject = obj => {
  for (const key in obj) return false;
  return true;
};
/**
 * 升序排序（数值类型比较）
 * @param name
 * @returns {Function}
 */
export const ascNumber = name => {
  return function(p, o) {
    let a;
    let b;
    if (typeof o === 'object' && typeof p === 'object' && o && p) {
      a = Number(o[name]);
      b = Number(p[name]);
      if (isNaN(a) && isNaN(b)) return 0;
      if (isNaN(a)) return -1;
      if (isNaN(b)) return 1;
      if (a === b) {
        return 0;
      }
      if (typeof a === typeof b) {
        return a < b ? 1 : -1;
      }
      return typeof a < typeof b ? 1 : -1;
    }
  };
};
/**
 * 降序排序（数值类型比较）
 * 方法调用：jsonData.sort(descNumber('orgid'));//根据orgid对jsonData对象数组进行排序
 */
export const descNumber = name => {
  return function(p, o) {
    let a;
    let b;
    if (typeof o === 'object' && typeof p === 'object' && o && p) {
      a = Number(o[name]);
      b = Number(p[name]);
      if (a === b) {
        return 0;
      }
      if (typeof a === typeof b) {
        return a < b ? -1 : 1;
      }
      return typeof a < typeof b ? -1 : 1;
    }
  };
};
/**
 * 降序排序（字符类型比较）
 * @param name
 * @returns {Function}
 */
export const descString = name => {
  return function(p, o) {
    let a;
    let b;
    if (typeof o === 'object' && typeof p === 'object' && o && p) {
      a = o[name];
      b = p[name];
      if (a === b) {
        return 0;
      }
      if (typeof a === typeof b) {
        return a < b ? -1 : 1;
      }
      return typeof a < typeof b ? -1 : 1;
    }
  };
};
/**
 * 获取占比
 * @param target
 * @param total
 * @returns {number}
 */
export const getPercent = (target, total) => {
  return total ? Number(((Number(target || 0) / Number(total)) * 100).toFixed(2)) : 0;
};
/**
 * 复合类型深度拷贝
 * @param obj
 * @returns {*}
 */
export const complexCopy = obj => {
  if (obj === null || typeof obj !== 'object') return obj;
  // if (obj instanceof Boolean) return new Boolean(obj.valueOf());
  // if (obj instanceof Number) return new Number(obj.valueOf());
  // if (obj instanceof String) return new String(obj.valueOf());
  // if (obj instanceof RegExp) return new RegExp(obj.valueOf());
  if (obj instanceof Date) return new Date(obj.valueOf());
  const cpObj = obj instanceof Array ? [] : {};
  for (const key in obj) cpObj[key] = complexCopy(obj[key]);
  return cpObj;
};
/**
 * 阿拉伯数字转中文数字,
 * 如果传入数字时则最多处理到21位，超过21位js会自动将数字表示成科学计数法，导致精度丢失和处理出错
 * 传入数字字符串则没有限制
 * @param {number|string} digit
 */
export const toZhDigit = digit => {
  digit = typeof digit === 'number' ? String(digit) : digit;
  const zh = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九'];
  const unit = ['千', '百', '十', ''];
  const quot = [
    '万',
    '亿',
    '兆',
    '京',
    '垓',
    '秭',
    '穰',
    '沟',
    '涧',
    '正',
    '载',
    '极',
    '恒河沙',
    '阿僧祗',
    '那由他',
    '不可思议',
    '无量',
    '大数',
  ];

  let breakLen = Math.ceil(digit.length / 4);
  let notBreakSegment = digit.length % 4 || 4;
  let segment;
  const zeroFlag = [];
  const allZeroFlag = [];
  let result = '';

  while (breakLen > 0) {
    if (!result) {
      // 第一次执行
      segment = digit.slice(0, notBreakSegment);
      const segmentLen = segment.length;
      for (let i = 0; i < segmentLen; i++) {
        if (segment[i] !== 0) {
          if (zeroFlag.length > 0) {
            result += `零${zh[segment[i]]}${unit[4 - segmentLen + i]}`;
            // 判断是否需要加上 quot 单位
            if (i === segmentLen - 1 && breakLen > 1) {
              result += quot[breakLen - 2];
            }
            zeroFlag.length = 0;
          } else {
            result += zh[segment[i]] + unit[4 - segmentLen + i];
            if (i === segmentLen - 1 && breakLen > 1) {
              result += quot[breakLen - 2];
            }
          }
        } else {
          // 处理为 0 的情形
          if (segmentLen === 1) {
            result += zh[segment[i]];
            break;
          }
          zeroFlag.push(segment[i]);
          continue;
        }
      }
    } else {
      segment = digit.slice(notBreakSegment, notBreakSegment + 4);
      notBreakSegment += 4;

      for (let j = 0; j < segment.length; j++) {
        if (segment[j] !== 0) {
          if (zeroFlag.length > 0) {
            // 第一次执行zeroFlag长度不为0，说明上一个分区最后有0待处理
            if (j === 0) {
              result += quot[breakLen - 1] + zh[segment[j]] + unit[j];
            } else {
              result += `零${zh[segment[j]]}${unit[j]}`;
            }
            zeroFlag.length = 0;
          } else {
            result += zh[segment[j]] + unit[j];
          }
          // 判断是否需要加上 quot 单位
          if (j === segment.length - 1 && breakLen > 1) {
            result += quot[breakLen - 2];
          }
        } else {
          // 第一次执行如果zeroFlag长度不为0, 且上一划分不全为0
          if (j === 0 && zeroFlag.length > 0 && allZeroFlag.length === 0) {
            result += quot[breakLen - 1];
            zeroFlag.length = 0;
            zeroFlag.push(segment[j]);
          } else if (allZeroFlag.length > 0) {
            // 执行到最后
            if (breakLen === 1) {
              result += '';
            } else {
              zeroFlag.length = 0;
            }
          } else {
            zeroFlag.push(segment[j]);
          }

          if (j === segment.length - 1 && zeroFlag.length === 4 && breakLen !== 1) {
            // 如果执行到末尾
            if (breakLen === 1) {
              allZeroFlag.length = 0;
              zeroFlag.length = 0;
              result += quot[breakLen - 1];
            } else {
              allZeroFlag.push(segment[j]);
            }
          }
          continue;
        }
      }
      --breakLen;
    }
    return result;
  }
};
/**
 * 格式化x轴标签
 * @param dataList
 * @param type
 * @param x
 * @returns {Array}
 */
export const formatAxis = (dataList, type, x = 'x') => {
  let list = [];
  if (dataList && dataList.length) {
    list = complexCopy(dataList);
    switch (type) {
      case 'month':
        list.map(item => {
          item[x] = item[x].substr(5, 7) ? `${Number(item[x].substr(5, 7))}月` : '--';
        });
        break;
      case 'quarter':
        list.map(item => {
          item[x] = item[x].substr(5, 7) ? `${toZhDigit(Number(item[x].substr(5, 7)))}季度` : '--';
        });
        break;
      case 'year':
        list.map(item => {
          item[x] = item[x] ? `${item[x]}年` : '--';
        });
        break;
      default:
    }
  }
  return list;
};
/**
 * 格式化x轴标签
 * @param val
 * @param type
 * @returns {string}
 */
export const formatAxisValue = (val, type) => {
  let formatValue = '';
  switch (type) {
    case 'month': {
      const month = val.substr(5, 7) ? `${Number(val.substr(5, 7))}月` : '--';
      formatValue = month === '1月' ? `\n \n ${month} \n ▲ \n ${val.substr(0, 4)}年` : month;
      break;
    }
    case 'quarter': {
      const quarter = val.substr(5, 7) ? `${toZhDigit(Number(val.substr(5, 7)))}季度` : '--';
      formatValue =
        quarter === '一季度' ? `\n \n ${quarter} \n ▲ \n ${val.substr(0, 4)}年` : quarter;
      break;
    }
    case 'year':
      formatValue = val ? `${val}年` : '--';
      break;
    default:
  }
  return formatValue;
};
/**
 * 将数组中的指定字段值转为数字
 * @param list
 * @param arrList
 * @returns {Array}
 */
export const stringDataToNum = (list = [], arrList = []) => {
  if (list.length) {
    list.map(item => {
      if (arrList.length) {
        arrList.map(v => (item[v] = Number(item[v])));
      }
    });
  }
  return list;
};
/**
 * 移除空children
 * @param list
 * @param childrenKey
 * @returns {Array}
 */
export const removeEmptyChildren = (list = [], childrenKey = 'children') => {
  if (list.length) {
    list.map(item => {
      if (item[childrenKey] && !item[childrenKey].length) {
        delete item[childrenKey];
      } else if (item[childrenKey] && item[childrenKey].length) {
        removeEmptyChildren(item[childrenKey], childrenKey);
      }
    });
  }
  return list;
};
/**
 * 获取目标节点id树
 * @param list
 * @param targetId
 * @param idKey
 * @param childrenKey
 */
export const getKeyList = (list = [], targetId, idKey = 'id', childrenKey = 'children') => {
  addKeyList(list, idKey, childrenKey);
  let keyList = [];
  searchKeyList(list, targetId, idKey, childrenKey, item => {
    keyList = item;
  });
  return keyList;
  // return searchKeyList(list, targetId, idKey, childrenKey);
};
// 查找目标id树
const searchKeyList = (list = [], targetId, idKey = 'id', childrenKey = 'children', callback) => {
  for (let i = 0; i < list.length; i++) {
    if (list[i][idKey] === targetId) {
      callback(list[i].keyList);
    }
    if (list[i][childrenKey]) {
      searchKeyList(list[i][childrenKey], targetId, idKey, childrenKey, callback);
    }
  }
};
// const searchKeyList = (list = [], targetId, idKey = 'id', childrenKey = 'children') => {
//   let keyList = [];
//   for (let i = 0; i < list.length; i++) {
//     if (list[i][idKey] === targetId) {
//       ({ keyList } = list[i]);
//       break;
//     } else if (list[i][childrenKey] && list[i][childrenKey].length) {
//       keyList = searchKeyList(list[i][childrenKey], targetId, idKey, childrenKey);
//       if (keyList.length) break; // 若子节点找到了，也要终止本次循环
//     }
//   }
//   return keyList;
// };
// 获取各节点id树
const addKeyList = (list = [], idKey = 'id', childrenKey = 'children', keyList = []) => {
  if (list.length) {
    list.map(item => {
      item.keyList = [...keyList, item[idKey]];
      if (item[childrenKey] && item[childrenKey].length) {
        addKeyList(item[childrenKey], idKey, childrenKey, [...keyList, item[idKey]]);
      }
    });
  }
  return list;
};
/**
 * 从树中查找指定id对象
 * @param data
 * @param targetId
 * @param idKey
 * @param callback
 * @param childrenKey
 */
export const loop = (data = [], targetId, idKey = 'id', callback, childrenKey = 'children') => {
  data.forEach((item, index, arr) => {
    if (item[idKey] === targetId) {
      return callback(item, index, arr);
    }
    if (item[childrenKey]) {
      return loop(item[childrenKey], targetId, idKey, callback, childrenKey);
    }
  });
};
/**
 * 获取搜索树 ExpandedKeys
 * @param list
 * @param searchKey
 * @param parentKey
 * @param searchValue
 * @param expandedKeys
 * @returns {Array}
 */
export const getSearchTreeExpandedKeys = (
  list = [],
  searchKey,
  parentKey,
  searchValue,
  expandedKeys = []
) => {
  if (list.length) {
    list.map(item => {
      if (searchValue && item[searchKey].indexOf(searchValue) > -1) {
        expandedKeys.push(item[parentKey]);
      }
      if (item.children && item.children.length) {
        getSearchTreeExpandedKeys(item.children, searchKey, parentKey, searchValue, expandedKeys);
      }
    });
  }
  return expandedKeys;
};
/**
 * 生成从minNum到maxNum的随机数
 * @param minNum
 * @param maxNum
 * @returns {number}
 */
export const randomNum = (minNum, maxNum) =>
  parseInt(Math.random() * (maxNum - minNum + 1) + minNum, 10);
/**
 * 数字补零
 * @param num
 * @param length
 * @returns {string}
 */
export const prefixInteger = (num, length) => {
  return (Array(length).join('0') + num).slice(-length);
};
